/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Author: byx
 * @Date: 2022-11-28 22:20:45
 * @LastEditors: byx
 * @LastEditTime: 2022-12-03 20:30:03
 * @version: 1.0
 * @Descripttion: wwww.byx1024.top
 */

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  DatePicker,
  Button,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'

import { ArticleStatus } from 'api/constants'

import styles from './index.module.scss'

import { delArticle, getArticles } from 'api/article'

import defaultImg from 'assets/error.png'
import Channel from 'components/Channel'
export default class ArticleList extends Component {
  columns = [
    {
      title: '封面',
      render(data) {
        // 无图，渲染默认图片
        if (data.cover.type === 0) {
          return <img src={defaultImg} alt="null" className="listImg" />
        }
        // 有图
        return <img src={data.cover.images[0]} alt="null" className="listImg" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = ArticleStatus.find(item => item.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                this.handleEdit(data.id)
              }}
            />
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                this.handleDelete(data.id)
              }}
            />
          </Space>
        )
      },
    },
  ]

  // 用户存放查询文章列表的所有参数
  reqParams = {
    page: 1,
    per_page: 10,
  }
  state = {
    articles: {},
  }

  render() {
    const { total_count, results, page, per_page } = this.state.articles
    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          {/* 表单结构 */}
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleStatus.map(item => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>

            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>

            <Form.Item label="日期" name="date">
              <DatePicker.RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        {/* 文章列表 */}
        <Card title={`根据筛选条件共查询到${total_count}条结果：`}>
          <Table
            columns={this.columns}
            dataSource={results}
            rowKey="id"
            pagination={{
              position: ['bottomCenter '],
              total: total_count,
              current: page,
              pageSize: per_page,
              // 每页大小 或者 页面改变时，触发的事件
              onChange: this.onChangeFn,
            }}
          />
        </Card>
      </div>
    )
  }

  // 修改操作
  handleEdit = id => {
    console.log('是否有id:', id)
    this.props.history.push(`/home/publish/${id}`)
  }
  // 删除操作
  handleDelete = id => {
    console.log(id)
    // 采用 confirm对话框
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章吗？',
      onOk: async () => {
        // 发送请求，删除文章
        await delArticle(id)
        // 重新获取用户列表
        this.getArticleList()
        message.success('删除成功')
      },
    })
  }
  // 分页触发方法
  onChangeFn = (page, pageSize) => {
    console.log(page, pageSize)
    this.reqParams.page = page
    this.reqParams.per_page = pageSize
    this.getArticleList()
  }
  // 搜索功能
  onFinish = ({ status, channel_id, date }) => {
    // 处理状态
    if (status !== -1) {
      this.reqParams.status = status
    } else {
      delete this.reqParams.status
    }
    // 处理频道
    if (channel_id !== undefined) {
      this.reqParams.channel_id = channel_id
    } else {
      delete this.reqParams.channel_id
    }
    // 处理时间
    if (date) {
      this.reqParams.begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.reqParams.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete this.reqParams.begin_pubdate
      delete this.reqParams.end_pubdate
    }
    console.log(this.reqParams)
    // 发请求
    // 查询前，需要让页码值重新为1
    this.reqParams.page = 1
    this.getArticleList()
  }

  // 进入页面的生命周期
  componentDidMount() {
    this.getArticleList()
  }

  // 获取文章列表数据
  async getArticleList() {
    const res = await getArticles(this.reqParams)
    this.setState({
      articles: res.data,
    })
  }
}
